package com.touchalachs.core.updateThread;

import android.graphics.Canvas;
import android.graphics.Paint;

import com.touchalachs.core.GameView;

public class UpdateNDrawThread extends UpdateThread {
	static final int FPS = 25;
	static final int MS_PER_FRAME = 1000 / FPS;
	private final GameView view;
	private volatile boolean running = false;

	public UpdateNDrawThread(GameView view) {
		this.view = view;
	}

	@Override
	public void setRunning(boolean run) {
		running = run;
	}

	@Override
	public void run() {
		long previousStartTime = System.currentTimeMillis();
		while (running) {
			if (!view.getHolder().getSurface().isValid() || view.getHolder().isCreating()) {
				continue;
			}
			long startTime = System.currentTimeMillis();
//			long updateDuration;
//			long drawDuration;
			Canvas c = null;
			try {
				c = view.getHolder().lockCanvas();
				synchronized (view.getHolder()) {
					float secSinceLastUpdate = (startTime - previousStartTime)/1000f;
//					System.out.println("secSinceLastUpdate:"+secSinceLastUpdate);
					view.update(secSinceLastUpdate);
//					updateDuration = System.currentTimeMillis()-startTime;
//					System.out.println("update took:"+updateDuration+"ms");
					view.draw(c);
					printFPS(c, secSinceLastUpdate);
//					drawDuration = System.currentTimeMillis()-startTime-updateDuration;
//					System.out.println("draw took:  "+drawDuration+"ms");
				}
			} finally {
				if (c != null) {
					view.getHolder().unlockCanvasAndPost(c);
				}
			}
			long endTime = System.currentTimeMillis();
			sleepRemainingFrameTime(endTime-startTime);
			previousStartTime = startTime;
		}

	}

	private static void printFPS(Canvas c, float secSinceLastUpdate) {
		Paint p = new Paint();
		p.setARGB(255, 255, 255, 0);
		p.setTextSize(30);
		int fps = (int)(1/secSinceLastUpdate);
		c.drawText(""+fps, 10, 32, p);
	}

	private static void sleepRemainingFrameTime(long workTime) {
		long sleepTime = MS_PER_FRAME - workTime;
//		if (sleepTime < 0){
//			sleepTime = 2;
//		}
//		System.out.println("sleeping for: "+sleepTime+"ms after "+workTime+"ms working");
		if (sleepTime > 0){
			try {
				sleep(sleepTime);
			} catch (Exception e) {}
		}
	}

}
